package alan.springboot2x.zkConfigStart.config;

import alan.springboot2x.zkConfigStart.annotation.EnableZkConfig;
import alan.springboot2x.zkConfigStart.scope.RefreshScopeRegistry;
import alan.springboot2x.zkConfigStart.zookeeper.CuratorUtil;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;

/**
 * @author: Alan
 * @date: 2021/4/3 12:36
 */
public class ConfigRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {
        Map<String, Object> defaultAttrs = metadata.getAnnotationAttributes(EnableZkConfig.class.getName(), true);

        Object mode = defaultAttrs.get("mode");
        if("zk".equals(mode.toString())){
            registerZkConfig(registry);
        }else if("redis".equals(mode.toString())){
            //待实现
        }

    }

    /**
     * 取代了@component
     * @param registry
     */
    private void registerZkConfig(BeanDefinitionRegistry registry) {
        BeanDefinitionBuilder curatorUtilBuilder = BeanDefinitionBuilder.genericBeanDefinition(CuratorUtil.class);
        BeanDefinitionBuilder refreshScopeRegistryBuilder = BeanDefinitionBuilder.genericBeanDefinition(RefreshScopeRegistry.class);
        registry.registerBeanDefinition( "alan.springboot2x.zkConfigStart.zookeeper.CuratorUtil", curatorUtilBuilder.getBeanDefinition() );
        registry.registerBeanDefinition("alan.springboot2x.zkConfigStart.scope.RefreshScopeRegistry",refreshScopeRegistryBuilder.getBeanDefinition());
    }

}
